package com.rick.oauth.service;

import client.AccountClientService;
import com.rick.oauth.domain.User;
import constant.AuthConstants;
import dto.AccountDTO;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import result.Result;
import result.ResultCode;

import javax.servlet.http.HttpServletRequest;


/**
 * 自定义用户认证和授权
 * @author Rick Jen
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private AccountClientService accountClientService;
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        User user = null;
        switch (clientId) {
            // 微信用户
            case AuthConstants.WECHAT_APP_CLIENT_ID:
                Result<AccountDTO> userRes = accountClientService.loadAccountByPhone(phone);
                if (ResultCode.USER_NOT_EXIST.getCode().equals(userRes.getCode())) {
                    throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
                }
                AccountDTO userDTO = userRes.getData();
                userDTO.setClientId(clientId);
                user = new User(userDTO);
                break;
            // APP会员
            case AuthConstants.APP_CLIENT_ID:
                break;
            default:
        }
        assert user != null;
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定!");
        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期!");
        }
        return user;
    }

}
